//
//  FinderViewController.m
//  CarFace
//
//  Created by dlios on 15-3-24.
//  Copyright (c) 2015年 蓝鸥科技. All rights reserved.
//

#import "FinderViewController.h"
#import "FindForum.h"
#import "Forum.h"
#import "ForumTableViewCell.h"
#import "SearchWebViewController.h"

@interface FinderViewController ()<UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate>

@property(nonatomic , retain)UITableView *tableView;
@property(nonatomic, retain)NSMutableArray *array;
@property(nonatomic, retain)NSString *strIP;
@end

@implementation FinderViewController

- (void)dealloc
{
    [_tableView release];
    [_array release];
    [_strIP release];
    [super dealloc];


}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    FindForum *finder = [[FindForum alloc]initWithFrame:CGRectMake(20, 30, self.view.frame.size.width - 40, 30)];
    finder.lable.text = @"论坛";
    finder.lable.font = [UIFont systemFontOfSize:17.0f];
    finder.search.placeholder = @"搜索关键字";
    [finder.button setTitle:@"取消" forState:UIControlStateNormal];
    [finder.button addTarget:self action:@selector(clickCancleButton:) forControlEvents:UIControlEventTouchUpInside];
    finder.search.delegate = self;
    
    [self.view addSubview:finder];
    [finder release];
    

    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(5, 65, self.view.frame.size.width - 10, self.view.frame.size.height - 65 - 49) style:UITableViewStylePlain];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.tableView addHeaderWithTarget:self action:@selector(addHeader:)];
    [self.tableView addFooterWithTarget:self action:@selector(addFooter:)];
    [self.tableView setHeaderRefreshingText:@"下拉刷新"];
    [self.tableView setFooterRefreshingText:@"网络加载中..."];
    [self.view addSubview:self.tableView];
    [_tableView release];
    [_tableView reloadData];
    
   
}

#pragma mark - 刷新的方法
- (void)addHeader:(UITableView *)header;
{
    __unsafe_unretained typeof(self) vc = self;
    // 添加下拉刷新头部控件
    [self.tableView addHeaderWithCallback:^{
        // 进入刷新状态就会回调这个Block
        // 模拟延迟加载数据，因此2秒后才调用（真实开发中，可以移除这段gcd代码）
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [vc.tableView reloadData];
            // 结束刷新
            [vc.tableView headerEndRefreshing];
            NSLog(@"KKkkk");
        });
    } dateKey:@"collection"];
    // dateKey用于存储刷新时间，也可以不传值，可以保证不同界面拥有不同的刷新时间
}

- (void)addFooter:(UITableView *)footer
{
    __unsafe_unretained typeof(self) vc = self;
    // 添加上拉刷新尾部控件
    [self.tableView addFooterWithCallback:^{
        [self.tableView addHeaderWithTarget:self action:@selector(searchBarSearchButtonClicked:)];
        
        // 模拟延迟加载数据，因此2秒后才调用（真实开发中，可以移除这段gcd代码）
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [vc.tableView reloadData];
            // 结束刷新
            [vc.tableView footerEndRefreshing];
            
        });
    }];
}

#pragma mark - tableView
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.array.count;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  static NSString *str = @"fgf";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:str];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:str]autorelease];
    }
    cell.textLabel.text = [[self.array objectAtIndex:indexPath.row] title];
    cell.textLabel.font = [UIFont systemFontOfSize:15.0f];
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.array != 0) {
      NSString *str = [[self.array objectAtIndex:indexPath.row]topicid];
        NSString *strIp = [NSString stringWithFormat: @"http://forum.app.autohome.com.cn/autov4.6/forum/club/topiccontent-a2-pm2-v4.6.0-t%@-o0-p1-s20-c1-nt0-fs0-sp0-al0-cw320.json", str];
        SearchWebViewController *searchVC = [[SearchWebViewController alloc]init];
        searchVC.ipAddress = strIp;
        [self presentViewController:searchVC animated:YES completion:^{
        }];
        
    }
}


#pragma mark - searchBar
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    
//    NSCharacterSet *set = [NSCharacterSet characterSetWithCharactersInString:@"／/：:`｀；,.?{}＊;（）()¥「」＂、[]［］｛｝{}＃％＋－#%-*+—=_\\|~＜～＞<>“$€^•@＃\'@$%^&*()_+'\"！!"];
//    NSString *trimmedString = [searchText stringByTrimmingCharactersInSet:set];
//    NSString *str1 = [NSString stringWithFormat:@"http://app.api.autohome.com.cn/autov4.6/sou/club.ashx?k=%@&r=0&p=1&s=20&bn=&v=4.6.1",trimmedString];
//    
//    NSString *str = [str1 stringByReplacingOccurrencesOfString:@" " withString:@""];
//    self.strIP = str;
//    NSLog(@"trimmedString:%@", trimmedString);
//    NSLog(@"str : %@", str);
    
    
     NSString *str1 = [NSString stringWithFormat:@"http://app.api.autohome.com.cn/autov4.6/sou/club.ashx?k=%@&r=0&p=1&s=20&bn=&v=4.6.1",searchText];
  self.strIP = [str1 stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    
//    self.strIP = str1;
    
    
    
    
    
    
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    searchBar.showsCancelButton = NO;
}

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
    searchBar.showsCancelButton = NO;
   [self.view endEditing:YES];
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manage GET:self.strIP parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSError *error = nil;
        id result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:&error];
        NSMutableArray *arr = [[result objectForKey:@"result"] objectForKey:@"topiclist"];
        NSLog(@"%@", arr);
        self.array = [NSMutableArray array];
        for (NSDictionary *dic in arr) {
            Forum *foru = [Forum objectWithDictionary:dic];
            [self.array addObject:foru];
        }
        [_tableView reloadData];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];
}

- (void)clickCancleButton:(UIButton *)button
{
 [self dismissViewControllerAnimated:YES completion:^{

 }];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
